package com.southwind.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.southwind.entity.OrderDetail;
import com.southwind.entity.OrderMaster;
import com.southwind.entity.ProductInfo;
import com.southwind.feign.ProductFeignClient;
import com.southwind.form.OrderForm;
import com.southwind.mapper.OrderDetailMapper;
import com.southwind.mapper.OrderMasterMapper;
import com.southwind.mapper.ProductInfoMapper;
import com.southwind.service.IOrderMasterService;
import com.southwind.vo.OrderMasterPageVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author admin
 * @since 2021-04-18
 */
@Service
@Slf4j
public class OrderMasterServiceImpl extends ServiceImpl<OrderMasterMapper, OrderMaster> implements IOrderMasterService {

    @Autowired
    private OrderMasterMapper orderMasterMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private ProductInfoMapper productInfoMapper;

    @Autowired
    private ProductFeignClient productFeignClient;

    /**
     * RocketMQ
     */
    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    /**
     * 创建订单。<br>1.插入order_master表，2.插入order_detail表，3.修改库存product_info表。
     * @param orderForm 封装前端参数
     * @return
     */
    @Override
    public String insert(OrderForm orderForm) {
        // 赋值到PO
        OrderMaster orderMaster = new OrderMaster();
        orderMaster.setBuyerName(orderForm.getName());
        orderMaster.setBuyerPhone(orderForm.getPhone());
        orderMaster.setBuyerAddress(orderForm.getAddress());
        orderMaster.setBuyerOpenid(orderForm.getId());
        orderMaster.setOrderStatus(0);
        orderMaster.setPayStatus(0);
        // 计算总价
        BigDecimal amount = BigDecimal.ZERO;
        List<OrderDetail> items = orderForm.getItems();
        for (OrderDetail item : items) {
            Integer productId = item.getProductId();
            // 查询单价
            ProductInfo productInfo = productInfoMapper.selectById(productId);
            BigDecimal productPrice = productInfo.getProductPrice();
            // BigDecimal做运算要调方法
            BigDecimal multiply = productPrice.multiply(new BigDecimal(item.getProductQuantity()));
            amount = amount.add(multiply);
        }
        orderMaster.setOrderAmount(amount);
        // 插入order_master表
        int insert = orderMasterMapper.insert(orderMaster);
        if (insert == 1) {
            for (OrderDetail item : items) {
                // 插入order_detail表
                Integer productId = item.getProductId();
                ProductInfo productInfo = productFeignClient.findById(productId);
                BeanUtils.copyProperties(productInfo, item);
                item.setOrderId(orderMaster.getOrderId()); // 插入order_master表后会自动回填主键id
                orderDetailMapper.insert(item);

                // 减库存
                try {
                    productFeignClient.subStock(productId, item.getProductQuantity());
                } catch (Exception e) {
                    log.info("减库存失败，productId={}，Exception={}", productId, e);
                    throw new RuntimeException("减库存失败！");
                }

            }
        }
        // 向mq发送消息
        this.rocketMQTemplate.convertAndSend("myTopic", "有新的订单");

        return orderMaster.getOrderId();
    }

    @Override
    public OrderMasterPageVO orderMasterVO(Long page, Long size) {
        Page<OrderMaster> orderMasterPage = new Page<>(page, size);
        QueryWrapper<OrderMaster> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("update_time");
        orderMasterMapper.selectPage(orderMasterPage, queryWrapper);
        List<OrderMaster> records = orderMasterPage.getRecords();
        OrderMasterPageVO orderMasterPageVO = new OrderMasterPageVO();
        orderMasterPageVO.setContent(records);
        orderMasterPageVO.setSize(orderMasterPage.getSize());
        orderMasterPageVO.setTotal(orderMasterPage.getTotal());
        return orderMasterPageVO;
    }
}
